<?php

namespace App\Http\Controllers\Admin;

use App\Jobs\SendWechatTemplate;
use App\Models\Book;
use App\Models\Order;
use App\Models\OrderExpressInfo;
use App\Models\OrderItem;
use App\Models\User;
use App\Models\UserAccountRecord;
use App\Services\UserCouponService;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use EasyWeChat;

class OrderController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->middleware('check_admin_login');
    }

    public function index(Request $request)
    {
        $page                         = intval($request->get('page',1));
        $page                         = max($page ,1);
        $page_size                    = intval($request->get('limit',10));
        $no                           = trim($request->get('no'));
        $start_time                   = intval($request->get('start_time'));
        $end_time                     = intval($request->get('end_time'));
        $pay_type                     = intval($request->get('pay_type'));
        $nickname                     = trim($request->get('nickname'));
        $state                        = intval($request->get('state'));//0全部 1已支付  2已发货  3已签收  -1已取消
        $user_id                      = intval($request->get('user_id'));

        $builder = Order::query()->with(['user']);

        if(!empty($nickname))
        {
            $builder->where('user_nickname','like','%'.$nickname.'%');
        }

        if(!empty($no))
        {
            $no = '%'.$no.'%';
            $builder->where('no','like',$no);
        }

        if(!empty($state))
        {
            $builder->where('state',$state);
        }
        else
        {
            $builder->where('state','!=',0);
        }

        if(!empty($start_time))
        {
            $builder->where('created_at','>=',$start_time);
        }

        if(!empty($user_id))
        {
            $builder->where('user_id',$user_id);
        }

        if(!empty($end_time))
        {
            $builder->where('created_at','<=',$end_time);
        }

        if(!empty($pay_type))
        {
            $builder->where('pay_type',$pay_type);
        }

        $columns = ['id','user_id','no','amount','created_at','pay_type','price','state'];
        $list = $builder->orderBy('id','desc')->paginate($page_size,$columns,'page',$page);



        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $items[] = [
                    'id'          => $item->id,
                    'user_id'     => $item->user_id,
                    'no'          => $item->no,
                    'amount'      => $item->amount,
                    'created_at'  => date('Y-m-d H:i:s',$item->created_at),
                    'pay_type'    => $item->pay_type,
                    'price'       => $item->price,
                    'state'       => $item->state,
                    'user_nickname' => $item->user->wechat_nickname,
                    'user_avatar' => $item->user->wechat_avatar,
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items" => $items
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function show(Request $request)
    {
        $order_id = intval($request->get('order_id'));
        if(empty($order_id))
        {
            return $this->err(1,200,'','参数错误');
        }
        $order = Order::query()->with(['items','user'])->where('id',$order_id)->first();
        //dd($order);

        $books = [];

        if(!empty($order->items))
        {
            foreach ($order->items as $v)
            {
                $book = Book::query()->with(['parent_catgeory','categories:categories.id,categories.title'])->where('id',$v->book_id)->first();
                //dd($book->categories);
                $books[] = [
                    'book_id'               => $v->book_id,
                    'book_title'            => $v->book_title,
                    'book_image'            => $v->book_image,
                    'book_author'           => $v->book_author,
                    'book_total_stock'      => $book->total_stock,
                    'book_old_price'        => $book->old_price,
                    'isbn'                  => $book->isbn,
                    'book_parent_category'  => optional($book->parent_catgeory)->title ? optional($book->parent_catgeory)->title : '',
                    'book_categories'       => $book->categories,
                    'type'                  => $v->type,
                    'price'                 => $v->price,
                ];
            }
        }

        $express_info = [];
        $express = OrderExpressInfo::query()->where('order_id',$order_id)->orderBy('id','desc')->first();
        if(!empty($express) && !empty($express->path_item_list))
        {
            $express_info = json_decode($express->path_item_list,true);
            foreach ($express_info as &$v)
            {
                $v['action_time'] = date('Y-m-d H:i:s',$v['action_time']);
            }
        }

        $result = [
            'id'                    => $order->id,
            'no'                    => $order->no,
            'price'                 => $order->price,  //实际支付价格
            'pay_type'              => $order->pay_type,  //支付类型 1=余额支付 2微信支付
            'address_receiver'      => $order->address_receiver,
            'address_mobile'        => $order->address_mobile,
            'address_province_name' => $order->address_province_name,
            'address_city_name'     => $order->address_city_name,
            'address_area_name'     => $order->address_area_name,
            'address'               => $order->address,
            'express_no'            => $order->express_no,
            'express_delivery_id'   => $order->express_delivery_id,
            'state'                 => $order->state,  //状态 1已支付  2已发货  3已签收  -1已取消
            'created_at'            => $order->created_at ? date('Y-m-d H:i:s',$order->created_at) : '',
            'pay_at'                => $order->pay_at ? date('Y-m-d H:i:s',$order->pay_at) : '',
            'send_at'               => $order->send_at ? date('Y-m-d H:i:s',$order->send_at) : '',
            'done_at'               => $order->done_at ? date('Y-m-d H:i:s',$order->done_at) : '',
            'cancel_at'             => $order->cancel_at ? date('Y-m-d H:i:s',$order->cancel_at) : '',
            'amount'                => $order->amount,  //图书数量
            'book_price'            => $order->book_price,  //图书的总价
            'fee_price'             => $order->fee_price,  //快递费
            'coupon_decr_price'     => $order->coupon_decr_price,  //红包抵扣金额
            'account_decr_price'    => $order->account_decr_price,  //账户余额支付抵扣金额
            'user_nickname'         => $order->user->wechat_nickname,
            'user_avatar'           => $order->user->wechat_avatar,
            'books'                 => $books,
            'express_info'          => $express_info,
        ];
        return $this->ok($result);
    }

    public function express(Request $request)
    {
        $order_id   = intval($request->get('order_id'));
        //$express_no = trim($request->get('express_no'));

        if(empty($order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        //$order = Order::query()->where('id',$order_id)->first();
        $order = Order::query()->with(['items'])->where('id',$order_id)->first();
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        if(!$order->is_express)
        {
            return $this->err(1,200,'','请先预约发货');
        }

        $first_book_title= '';
        foreach ($order->items as $k=>$v)
        {
            if($k == 0)
            {
                $first_book_title = $v->book_title;
            }

            Book::query()->where('id',$v->book_id)->increment('sales_total');
        }


        $user = User::find($order->user_id);
        $ret = $order->update(['state' => 2,'send_at' => $this->time]);
        $user->increment('buy_orders_num');
        if($ret)
        {
            if(!empty($user->recommend_user_id) && !$user->is_recommend_coupon)
            {
                //给推荐人发送红包奖励
                $userCouponService = new UserCouponService();
                $userCouponService->getCoupon($user->recommend_user_id,1);

                $user->update(['is_recommend_coupon'=>1]);

                //给推荐人发送微信消息
                //使用异步队列
                $job_params = [
                    'user_id'           => $user->recommend_user_id,
                    'template_id'       => 'IZIf7iWG7W_yZuapB6bSfo4do97wzB_JIEH6O9CyAiQ',
                    'coupon_type'       => 1,
                    'type'              => 1,  //下单买书
                    'wechat_nickname'  => $user->wechat_nickname,
                ];
                dispatch(new SendWechatTemplate($job_params));
            }

            $sms = app('easysms');
            try {
                $sms->send($order->address_mobile,[
                    'template' => 'SMS_163055952',
                    'data' => [
                        'name' => $order->address_receiver
                    ],
                ]);
            } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                $message = $exception->getException('aliyun')->getMessage();
                dd($message);
            }


            //发送推送消息
            $keyword4 = "《".$first_book_title."》...共".$order->amount.'本书';
            $officialAccount = EasyWeChat::officialAccount(); // 公众号
            $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
            if(!empty($wechat_user))
            {
                $openid = $wechat_user->openid;

                $first = "您购买的书已通过「中通快递」发货，请注意查收\r\n";
                $officialAccount->template_message->send([
                    'touser'        => $openid,
                    'template_id'   => 'eK9uUTzVBuhf-hzIzF-n5IxxYjYieVL8BOR7BGeLutU',
                    'url'  => '',
                    'miniprogram' => [
                        'appid'     => config('wechat.mini_program.default.app_id'),
                        'path'      => '/pages/order/order-detail/order-detail?id='.$order->id,
                    ],
                    'data' => [
                        'first'     => $first,
                        'keyword1'  => $order->no,
                        'keyword2'  => date('Y-m-d H:i:s',$order->created_at),
                        'keyword3'  => $order->price.'元',
                        'keyword4'  => $keyword4."\r\n",
                        'remark'    => '点击“详情”可查看订单与物流进度。'
                    ],
                ]);
            }

            return $this->ok([],'操作成功');
        }
        return $this->err(1,200,'','操作失败');
    }

    /**
     * 预约快递进行发货
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function send(Request $request)
    {
        $order_id = intval($request->get('order_id'));
        if(empty($order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = Order::query()->with(['items'])->where('id',$order_id)->first();
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state != 1)
        {
            return $this->err(1,200,'','状态错误,无法发货');
        }

        if(!empty($order->express_waybill_id) || $order->is_express)
        {
            return $this->ok(['express_waybill_id' => $order->express_waybill_id,'delivery_id' => $order->express_delivery_id],'操作成功');
        }

        $detail_list = [];
        $goodsName = [];
        foreach ($order->items as $k=>$v)
        {
            $goodsName[] = $v->book_title;
            $detail_list[] = [
                'name' => $v->book_title,
                'count' => 1
            ];
            //$imgUrl = $v->book_image;
        }

        $user = User::find($order->user_id);
        $openid = $user->wechat_openid;
        //$openid = 'oykEg5WGTi181uPuJUX5jT7jlvr4';

        $delivery_id = 'ZTO';
        $biz_id = 'ZTO531558226398055';
        $data = [
            'order_id'      => $order->no,
            'openid'        => $openid,
            'delivery_id'   => $delivery_id,
            'biz_id'        => $biz_id,
            'custom_remark' => '',
            'sender' => [
                'name'      => '快鱼二手书',
                'tel'       => '',
                'mobile'    => '15888825922',
                'company'   => '',
                'postCode'  => '',
                'country'   => '中国',
                'province'  => '浙江省',
                'city'      => '杭州市',
                'area'      => '余杭区',
                'address'   => '万科未来城',
            ],
            'receiver' => [
                'name'      => $order->address_receiver,
                'tel'       => '',
                'mobile'    => $order->address_mobile,
                'company'   => '',
                'postCode'  => '',
                'country'   => '中国',
                'province'  => $order->address_province_name,
                'city'      => $order->address_city_name,
                'area'      => $order->address_area_name,
                'address'   => $order->address,
            ],
            'cargo' => [
                'count'         => 1,
                'weight'        => 2,
                'space_x'       => 30,
                'space_y'       => 30,
                'space_z'       => 30,
                'detail_list'   => $detail_list
            ],
            'shop' => [
                'wxa_path'      => '/pages/order/order-detail/order-detail?id='.$order_id,
                'img_url'        => 'https://book-shop.oss-cn-hangzhou.aliyuncs.com/images/wuliuzhushou.png',
                //'goods_name'    => implode(',',$goodsName),
                'goods_name'    => '图书',
                'goods_count'   => $order->amount,
            ],
            'insured' => [
                'use_insured'   => 0,
                'insured_value' => 0
            ],
            'service' => [
                'service_type' => 0,
                'service_name' => '标准快件'
            ]
        ];

        $service = new WechatService();
        $ret = $service->add_order($data);
        if(!empty($ret['waybill_id']))
        {
            $order->update([
                'expree_waybill_data'   => json_encode($ret),
                'express_waybill_id'    => $ret['waybill_id'],
                'is_express'            => 1,
                'express_no'            => $ret['waybill_id'],
            ]);

            return $this->ok(['express_waybill_id' => $ret['waybill_id'], 'delivery_id' => $delivery_id, 'order_no' => $order->no],'操作成功');
        }

        $order->update([
            'expree_waybill_data_error' => json_encode($ret),
        ]);
        return $this->err(1,200,'','操作失败');
    }

    public function cancelExpress(Request $request)
    {
        $order_id = intval($request->get('order_id'));
        if(empty($order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = Order::query()->where('id',$order_id)->first();
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state != 1)
        {
            return $this->err(1,200,'','状态错误,无法申请取消');
        }

        if(empty($order->express_waybill_id))
        {
            return $this->err(1,200,'','操作失败');
        }

        $service = new WechatService();
        $ret = $service->cancelOrder($order->no,$order->user_openid,$order->express_waybill_id,$order->express_delivery_id);
        //dd($ret);
        if(!$ret['errcode'])
        {
            return $this->ok([],'取消运单成功');
        }
        return $this->err(1,200,'','操作失败');
    }

    public function refund(Request $request)
    {
        $order_id = intval($request->get('order_id'));
        if(empty($order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = Order::query()->where('id',$order_id)->first();
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state != 1)
        {
            return $this->err(1,200,'','状态错误,无法申请退款');
        }

        if($order->refund_status > 0)
        {
            return $this->err(1,200,'','该订单已经申请过退款，请勿重复申请');
        }

        $user = User::find($order->user_id);
        if($order->pay_type  == 1)
        {
            DB::beginTransaction();    //主事务
            try {
                // 将订单退款状态改为退款成功
                $order->update([
                    'refund_status' => 2,
                    'updated_at'    => $this->time,
                    'state'         => -1,
                ]);

                //用户账户余额
                $user->increment('account',round($order->price,1));
                //账户余额记录
                UserAccountRecord::create([
                    'type'    => 2,
                    'account' => round($order->price,1),
                    'remark'  => '订单取消',
                    'user_id' => $order->user_id,
                ]);

                $item = OrderItem::query()->with(['book'])->where('order_id',$order->id)->orderBy('id','asc')->first();
                $keyword2 = "《".$item->book->title."》...共".$order->amount.'本书';

                $officialAccount = EasyWeChat::officialAccount(); // 公众号
                $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
                if(!empty($wechat_user))
                {
                    $openid = $wechat_user->openid;

                    $first = "您的买书订单取消成功，已退款\r\n";
                    $officialAccount->template_message->send([
                        'touser'        => $openid,
                        'template_id'   => 'eAewZ_8ibUx3OjnQdL2WJQTXIAPC5mgMQn7iS9QXlRg',
                        'url'  => '',
                        'miniprogram' => [
                            'appid'     => config('wechat.mini_program.default.app_id'),
                            'path'      => '/pages/order/order-detail/order-detail?id='.$order->id,
                        ],
                        'data' => [
                            'first'     => $first,
                            'keyword1'  => $order->price.'元',
                            'keyword2'  => $keyword2,
                            'keyword3'  => $order->no."\r\n",
                            'remark'    => '退款将原路退回到您的支付账户，请注意查收。（微信支付退款到账时间，请以微信通知为准）'
                        ],
                    ]);
                }

                $items = OrderItem::query()->select(['book_id','order_id','type'])->where('order_id',$order->id)->get();
                foreach ($items as $v)
                {
                    $book = Book::find($v->book_id);
                    if($v->type == 1)
                    {
                        $book->increment('new_book_stock', 1);
                    }
                    elseif($v->type == 2)
                    {
                        $book->increment('good_book_stock', 1);
                    }
                    elseif($v->type == 3)
                    {
                        $book->increment('medium_book_stock', 1);
                    }
                    elseif($v->type == 4)
                    {
                        $book->increment('medium_book_stock2', 1);
                    }
                    elseif($v->type == 5)
                    {
                        $book->increment('medium_book_stock3', 1);
                    }
                    elseif($v->type == 6)
                    {
                        $book->increment('medium_book_stock4', 1);
                    }
                    elseif($v->type == 7)
                    {
                        $book->increment('medium_book_stock5', 1);
                    }
                    elseif($v->type == 8)
                    {
                        $book->increment('medium_book_stock6', 1);
                    }

                    //加总库存
                    $book->addStock(1);
                }

                DB::commit();
                return $this->ok([],'订单取消成功');
            } catch (\Exception $e) {
                DB::rollBack();
                //echo $e->getMessage();
                return $this->err(1,200,$e->getMessage(),'申请退款失败');
            }
        }
        else
        {
            DB::beginTransaction();    //主事务
            try {
                // 将订单退款状态改为已申请退款
                $order->update([
                    'refund_status' => 1,
                    'updated_at'    => $this->time,
                ]);

                // 生成退款订单号
                $refundNo = Order::findAvailableNo();
                app('wechat_pay')->refund([
                    'out_trade_no'  => $order->no, // 之前的订单流水号
                    'total_fee'     => $order->price * 100, //原订单金额，单位分
                    'refund_fee'    => $order->price * 100, // 要退款的订单金额，单位分
                    //'total_fee'     => 0.01 * 100, //原订单金额，单位分
                    //'refund_fee'    => 0.01 * 100, // 要退款的订单金额，单位分
                    'out_refund_no' => $refundNo, // 退款订单号
                    // 微信支付的退款结果并不是实时返回的，而是通过退款回调来通知，因此这里需要配上退款回调接口地址
                    //'notify_url' => 'https://requestbin.leo108.com/tpu2z3tp' // 由于是开发环境，需要配成 requestbin 地址
                    'notify_url' => route('payment.wechat.refund_notify'),
                ]);

                $item = OrderItem::query()->with(['book'])->where('order_id',$order->id)->orderBy('id','asc')->first();
                $keyword2 = "《".$item->book->title."》...共".$order->amount.'本书';

                $officialAccount = EasyWeChat::officialAccount(); // 公众号
                $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
                if(!empty($wechat_user))
                {
                    $openid = $wechat_user->openid;

                    $first = "您的买书订单取消成功，已退款\r\n";
                    $officialAccount->template_message->send([
                        'touser'        => $openid,
                        'template_id'   => 'eAewZ_8ibUx3OjnQdL2WJQTXIAPC5mgMQn7iS9QXlRg',
                        'url'  => '',
                        'miniprogram' => [
                            'appid'     => config('wechat.mini_program.default.app_id'),
                            'path'      => '/pages/order/order-detail/order-detail?id='.$order->id,
                        ],
                        'data' => [
                            'first'     => $first,
                            'keyword1'  => $order->price.'元',
                            'keyword2'  => $keyword2,
                            'keyword3'  => $order->no."\r\n",
                            'remark'    => '退款将原路退回到您的支付账户，请注意查收。（微信支付退款到账时间，请以微信通知为准）'
                        ],
                    ]);
                }

                DB::commit();
                return $this->ok([]);
            } catch (\Exception $e) {
                DB::rollBack();
                //echo $e->getMessage();
                return $this->err(1,200,$e->getMessage(),'申请退款失败');
            }
        }
    }
}
